<?php
// +----------------------------------------------------------------------
// | 授权系统 - 产品管理控制器
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace api\modules\admin\controllers\license;

use api\modules\admin\AuthController;
use api\utils\libs\CommonAction;
use common\models\system\Product;
use yii\db\ActiveQuery;

/**
 * 产品管理控制器
 */
class ProductController extends AuthController
{
    use CommonAction;
    
    protected string $model = Product::class;
    protected bool $validate = true;
    
    protected function listQuery(ActiveQuery $query): ActiveQuery
    {
        return $query->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC]);
    }
    
    /**
     * 产品详情
     */
    public function actionDetail()
    {
        $id = $this->request->get('id');
        $product = Product::findOne($id);
        
        if (!$product) {
            return $this->error('产品不存在');
        }
        
        $data = $product->toArray();
        $data['feature_list'] = $product->getFeatureList();
        $data['pricing_data'] = $product->getPricingData();
        
        return $this->success('', $data);
    }
    
    /**
     * 创建产品
     */
    public function actionCreate()
    {
        $product = new Product();
        $data = $this->request->post();
        
        $data['created_by'] = $this->user_id;
        
        // 处理JSON字段
        if (isset($data['features']) && is_array($data['features'])) {
            $data['features'] = json_encode($data['features']);
        }
        if (isset($data['pricing']) && is_array($data['pricing'])) {
            $data['pricing'] = json_encode($data['pricing']);
        }
        
        $product->setAttributes($data);
        
        if ($product->save()) {
            return $this->success('产品创建成功', ['id' => $product->id]);
        }
        
        return $this->error('产品创建失败');
    }
    
    /**
     * 更新产品
     */
    public function actionUpdate()
    {
        $id = $this->request->post('id');
        $product = Product::findOne($id);
        
        if (!$product) {
            return $this->error('产品不存在');
        }
        
        $data = $this->request->post();
        $data['updated_by'] = $this->user_id;
        
        // 处理JSON字段
        if (isset($data['features']) && is_array($data['features'])) {
            $data['features'] = json_encode($data['features']);
        }
        if (isset($data['pricing']) && is_array($data['pricing'])) {
            $data['pricing'] = json_encode($data['pricing']);
        }
        
        $product->setAttributes($data);
        
        if ($product->save()) {
            return $this->success('产品更新成功');
        }
        
        return $this->error('产品更新失败');
    }
    
    /**
     * 删除产品
     */
    public function actionDelete()
    {
        $id = $this->request->post('id');
        $product = Product::findOne($id);
        
        if (!$product) {
            return $this->error('产品不存在');
        }
        
        // 检查是否有关联的授权
        $licenseCount = \common\models\system\License::find()
            ->where(['product_id' => $id])
            ->count();
        
        if ($licenseCount > 0) {
            return $this->error('该产品有关联的授权，无法删除');
        }
        
        if ($product->delete()) {
            return $this->success('产品删除成功');
        }
        
        return $this->error('产品删除失败');
    }
    
    /**
     * 获取所有产品列表（用于下拉选择）
     */
    public function actionAll()
    {
        $products = Product::find()
            ->where(['status' => Product::STATUS_NORMAL])
            ->select(['id', 'product_code', 'product_name'])
            ->orderBy(['sort' => SORT_ASC])
            ->asArray()
            ->all();
        
        return $this->success('', ['list' => $products]);
    }
}

